package com.vf.admin.miaodong.service.impl;

import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.miaodong.dao.AfterOrderDao;
import com.vf.admin.miaodong.dao.AfterPrivilegeDao;
import com.vf.admin.miaodong.dao.AfterUserDao;
import com.vf.admin.miaodong.entity.AppPrivilege;
import com.vf.admin.miaodong.service.AfterPrivilegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 贵族等级
 */
@Service
public class AfterPrivilegeServiceImpl implements AfterPrivilegeService {

    @Autowired
    AfterUserDao afterUserDao;

    @Autowired
    AfterPrivilegeDao afterPrivilegeDao;

    @Autowired
    AfterOrderDao afterOrderDao;

    /**
     * 查询列表
     */
    @Override
    public List<AppPrivilege> list(Map<String, Object> paraMap, SplitPageBean splitPage) {
        return afterPrivilegeDao.list(paraMap,splitPage);
    }

    /**
     * 详情
     */
    @Override
    public AppPrivilege get(Integer id) {
        return afterPrivilegeDao.get(id);
    }

    /**
     * 添加/修改
     */
    @Override
    public void save(AppPrivilege appPrivilege) {
        afterPrivilegeDao.save(appPrivilege);
    }

    /**
     * 删除
     */
    @Override
    public void del(Integer id) {
        afterPrivilegeDao.del(id);
    }

    public String getIpAdrress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /*
    @Transactional
    @Override
    public Result NobleTopUpZFB(Integer userid, Integer guizu) {
        AppUser byId = appUserDao.get(userid);
        if (byId == null) {
            return errorJSON("用户不存在");
        }
        AppPrivilege appPrivilege = appPrivilegeDao.get(guizu);
        if (appPrivilege == null) {
            return errorJSON("贵族等级不存在");
        }
        int money = appPrivilege.getMoney();
        try {
            String orderNumber = System.currentTimeMillis() + "" + MD5Util.getSix(5);

            String orderStr = "";
            //金额
            if (money <= 0.0) {
                return errorJSON("订单金额不能小于1");
            }
            //实例化客户端
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.gateway_url, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            AlipayTradeAppPayRequest ali_request = new AlipayTradeAppPayRequest();
            //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            // model.setBody("支付宝充值"+pkOrderForm.getActualMoney() +"元");                        							//商品信息
            model.setSubject("支付宝充值");                                                                //商品名称
            model.setOutTradeNo(orderNumber);                    //商户订单号(自动生成)
            model.setTimeoutExpress("30m");
            model.setTotalAmount(money+"");                  //money.toString()                      //支付金额
            model.setProductCode("QUICK_MSECURITY_PAY");                                                //销售产品码
            ali_request.setBizModel(model);
            ali_request.setNotifyUrl(AlipayConfig.notify_url);                                        //回调地址
            AlipayTradeAppPayResponse response = client.sdkExecute(ali_request);
            orderStr = response.getBody();
//            JSONObject JSONObject = new JSONObject(orderStr);
            System.err.println(orderStr + "-------------------------");
            Map<String, Object> mm = new HashMap<>();
            mm.put("pay", orderStr);

            AppOrder appOrder = new AppOrder();
            if (StringUtils.isEmpty(byId.getNick())) {
                appOrder.setNick("无");
            } else {
                appOrder.setNick(byId.getNick());
            }
            appOrder.setCreatetime(new Date());
            appOrder.setMoney(money);
            appOrder.setOrdernum(orderNumber);
            appOrder.setNum(0);
            appOrder.setPhone(byId.getLoginname());
            if (StringUtils.isEmpty(byId.getPic())) {
                appOrder.setPic("无");
            } else {
                appOrder.setPic(byId.getPic());
            }
            appOrder.setState(1);
            appOrder.setStatus(1);
            appOrder.setUserid(userid);
            appOrder.setType(1);
            appOrder.setUserid(Integer.valueOf(userid));
            appOrderDao.save(appOrder);

            return sucess(mm);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void alipayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

    }
*/

 /*   @Transactional
    @Override
    public Result NobleTopUpWX(Integer userid, Integer guizu) {
        AppUser byId = appUserDao.get(userid);
        if (byId == null) {
            return errorJSON("用户不存在");
        }
        AppPrivilege appPrivilege = appPrivilegeDao.get(guizu);
        if (appPrivilege == null) {
            return errorJSON("贵族等级不存在");
        }
        Double money = appPrivilege.getMoney();

        String orderNumber = System.currentTimeMillis() + "" + MD5Util.getSix(5);
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        //应用APPID
        parameters.put("appid", WxConfigUtil.APPID);
        //微信支付分配的商户号
        parameters.put("mch_id", WxConfigUtil.MCH_ID);
        //随机字符串，不长于32位
        parameters.put("nonce_str", PayCommonUtil.CreateNoncestr());
        //商品描述
        parameters.put("body", "语聊微信付款");
        //订单id
        parameters.put("out_trade_no", orderNumber);
        //默认人民币：CNY
        parameters.put("fee_type", "CNY");
        //订单总金额
        Integer aa = (int) (money * 100);
        parameters.put("total_fee", aa);
        try {
            parameters.put("spbill_create_ip", getIpAdrress(request));
            //	parameters.put("spbill_create_ip",Utils.getIpAddr(request));
        } catch (Exception e1) {
            return errorJSON("用户ip错误");
        }
        //接收微信支付异步通知回调地址
        parameters.put("notify_url", WxConfigUtil.notify_url);
        //支付类型
        parameters.put("trade_type", "APP");
        //设置签名
        String sign = PayCommonUtil.createSign("UTF-8", parameters);
        parameters.put("sign", sign);
        //封装请求参数结束
        String requestXML = PayCommonUtil.getRequestXml(parameters);
        //调用统一下单接口
        String result = PayCommonUtil.httpsRequest(WxConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
        System.out.println("\n" + result);
        try {
            *//**统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。参与签名的字段名为appId，partnerId，prepayId，nonceStr，timeStamp，package。注意：package的值格式为Sign=WXPay**//*
            Map<String, String> map = XMLUtil.doXMLParse(result);
            SortedMap<Object, Object> parameterMap2 = new TreeMap<Object, Object>();
            parameterMap2.put("appid", WxConfigUtil.APPID);
            parameterMap2.put("partnerid", WxConfigUtil.MCH_ID);
            parameterMap2.put("prepayid", map.get("prepay_id"));
            parameterMap2.put("package", "Sign=WXPay");
            parameterMap2.put("noncestr", PayCommonUtil.CreateNoncestr());
            //本来生成的时间戳是13位，但是ios必须是10位，所以截取了一下
            parameterMap2.put("timestamp", Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10)));
            String sign2 = PayCommonUtil.createSign("UTF-8", parameterMap2);
            parameterMap2.put("sign", sign2);


            AppOrder appOrder = new AppOrder();
            if (StringUtils.isEmpty(byId.getNick())) {
                appOrder.setNick("无");
            } else {
                appOrder.setNick(byId.getNick());
            }
            appOrder.setCreatetime(new Date());
            appOrder.setMoney(money);
            appOrder.setOrdernum(orderNumber);
            appOrder.setNum(0);
            appOrder.setPhone(byId.getLoginname());
            if (StringUtils.isEmpty(byId.getPic())) {
                appOrder.setPic("无");
            } else {
                appOrder.setPic(byId.getPic());
            }
            appOrder.setState(1);
            appOrder.setStatus(1);
            appOrder.setUserid(userid);
            appOrder.setType(1);
            appOrder.setUserid(Integer.valueOf(userid));
            appOrderDao.save(appOrder);


            return sucess(parameterMap2);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
*/



}
